import { useDark } from '@vueuse/core';
import { watch, Ref } from 'vue';

// 为UEditor添加全局类型声明
declare global {
  interface Window {
    UE?: {
      getEditor: (id: string) => any;
    };
  }
}

/**
 * 为UEditor添加暗黑模式支持
 * @param editorId 编辑器ID
 */
export const useUEditorDarkMode = (editorId: string | Ref<string>) => {
  // 获取当前暗黑模式状态
  const isDark = useDark({
    storageKey: 'useDarkKey',
    valueDark: 'dark',
    valueLight: 'light'
  });

  // 动态加载暗黑模式样式表
  const loadDarkStyles = () => {
    const darkStyleId = 'ueditor-dark-style';
    if (!document.getElementById(darkStyleId)) {
      const link = document.createElement('link');
      link.id = darkStyleId;
      link.rel = 'stylesheet';
      link.href = `${import.meta.env.VITE_APP_CONTEXT_PATH}/static/UEditorPlus/themes/default/css/ueditor-dark.css`;
      document.head.appendChild(link);
    }
  };

  // 应用暗黑模式到编辑器
  const applyDarkMode = (editor: any, isDarkMode: boolean) => {
    if (!editor) return;

    try {
      // 获取编辑器iframe
      const iframe = editor.iframe || document.getElementById(`${editor.key}_iframe`);
      if (!iframe) return;

      // 获取iframe内的document对象
      const iframeDoc = iframe.contentDocument || iframe.contentWindow?.document;
      if (!iframeDoc) return;

      // 移除之前可能存在的暗黑模式类
      iframeDoc.documentElement.classList.remove('dark');
      iframeDoc.body.style.backgroundColor = '';
      iframeDoc.body.style.color = '';

      // 如果是暗黑模式，应用暗黑样式
      if (isDarkMode) {
        iframeDoc.documentElement.classList.add('dark');
        iframeDoc.body.style.backgroundColor = '#ffffff';
        iframeDoc.body.style.color = '#000000';
      }

      // 处理编辑器容器
      const editorContainer = editor.container || document.getElementById(editor.key);
      if (editorContainer) {
        if (isDarkMode) {
          editorContainer.classList.add('dark');
        } else {
          editorContainer.classList.remove('dark');
        }
      }
    } catch (error) {
      console.error('应用暗黑模式到UEditor失败:', error);
    }
  };

  // 监听暗黑模式变化
  const stopWatch = watch(
    () => isDark.value,
    (newIsDark) => {
      const id = typeof editorId === 'object' ? editorId.value : editorId;
      const editor = window.UE?.getEditor(id);
      if (editor) {
        applyDarkMode(editor, newIsDark);
      }
    }
  );

  // 初始化函数 - 在组件的onMounted中调用
  const initialize = () => {
    loadDarkStyles();
  };

  // 手动应用暗黑模式 - 在编辑器初始化完成后调用
  const applyDarkModeManually = () => {
    const id = typeof editorId === 'object' ? editorId.value : editorId;
    const editor = window.UE?.getEditor(id);
    if (editor) {
      applyDarkMode(editor, isDark.value);
    }
  };

  // 清理函数 - 在组件的onBeforeUnmount中调用
  const cleanup = () => {
    stopWatch();
  };

  return {
    isDark,
    initialize,
    cleanup,
    applyDarkModeManually
  };
};

/**
 * 扩展UEditor配置，添加暗黑模式支持
 * @param config 原始配置对象
 * @returns 扩展后的配置对象
 */
export const extendUEditorConfig = (config: any) => {
  const isDark = useDark({
    storageKey: 'useDarkKey',
    valueDark: 'dark',
    valueLight: 'light'
  });

  // 扩展默认配置
  return {
    ...config,
    // 添加暗黑模式配置
    enableDarkMode: isDark.value
  };
}; 